<?php
/* This script (re)creates the files required from a base project.
 */
require_once dirname(__FILE__) . '/config.ini.php';

removeData("$targetRoot/$classesPath");
copyData($classesPath, $classesPath);

$parts = parts($managePath);
removeData("$targetRoot/$parts[0]/__$parts[1]");
copyData($managePath, "$parts[0]/__$parts[1]");

removeData("$targetRoot/$libraryPath");
copyData($libraryPath, $libraryPath);

$parts = parts($includesPath);
removeData("$targetRoot/$parts[0]/__$parts[1]");
copyData($includesPath, "$parts[0]/__$parts[1]");

echo "Done.\n";

function removeData($dir) {
  $dh = opendir($dir);
  if (!$dh) {
    echo "ERROR: Couldn't open directory: $dir\n";
    return;
  }

  while (($file = readdir($dh)) !== false) {
    if ($file[0] == '.') {
      continue;
    }
    
    $name = "$dir/$file";
    if (is_dir($name)) {
      removeData("$dir/$file");
      continue;
    }
    unlink($name);
  }

  closedir($dh);
}

function copyData($in, $out) {
  global $sourceRoot, $targetRoot;

  $dir = "$sourceRoot/$in";
  $dh = opendir($dir);
  if (!$dh) {
    echo "ERROR: Couldn't open directory: $dir\n";
    return;
  }

  while (($file = readdir($dh)) !== false) {
    if ($file[0] == '.') {
      continue;
    }

    $name = "$dir/$file";

    if (is_dir($name)) {
      if ($name != "$targetRoot/$out/$file") {
        //echo " -> $name\n";
        copyData("$in/$file", "$out/$file");
      }
      continue;

    } else {
      $fp = file_get_contents($name);
      if ($fp === false) {
        echo "ERROR: Failed to read: $name\n";
      } else {
        copy("$name", "$targetRoot/$out/$file");
      }
    }
  }

  closedir($dh);
}

function parts($path) {
  $pos = strrpos($path, '/');
  return array(substr($path, 0, $pos), substr($path, $pos + 1));
}
?>
